import React, { useState, useEffect } from 'react';
import './RankingPage.css';
import Header from '../Header/Header';
import ApiService from '../../api/index';
import shdyjImg from '../../assets/login/shdyj.png';
import mqdphbImg from '../../assets/phb/phbback.png';
import headerImage from '../../assets/phb/phbheader.png';
import iconBackImg from '../../assets/icon/icon-back.png';

// 导入所有图标图片
import hshsImg from '../../assets/icon/hshs.png';
import gskhImg from '../../assets/icon/gskh.png';
import hyllImg from '../../assets/icon/hyll.png';
import bbgsImg from '../../assets/icon/bbgs.png';
import ssryImg from '../../assets/icon/ssry.png';
import myflImg from '../../assets/icon/myfl.png';
import jzjlImg from '../../assets/icon/jzjl.png';
import szjxImg from '../../assets/icon/szjx.png';
import jyczImg from '../../assets/icon/jycz.png';
import hwylImg from '../../assets/icon/hwyl.png';
import jbaxImg from '../../assets/icon/jbax.png';
import thggImg from '../../assets/icon/thgg.png';
import ylghImg from '../../assets/icon/ylgh.png';
import plrsImg from '../../assets/icon/plrs.png';
import nnyyImg from '../../assets/icon/nnyy.png';

// 导入排名图片
import dymImg from '../../assets/icon/dym.png'; // 第一名
import demImg from '../../assets/icon/dem.png'; // 第二名
import dsmImg from '../../assets/icon/dsm.png'; // 第三名

/**
 * 图标和文字数据数组
 * 包含15个图标的图片和对应的文字描述
 */
const imagesText = [{
  img: hshsImg,
  text: '好事"花生"',
}, {
  img: gskhImg,
  text: '杠上开"发"',
}, {
  img: hyllImg,
  text: '好运"莲连"',
}, {
  img: bbgsImg,
  text: '步步高升',
}, {
  img: ssryImg,
  text: '"柿柿"如意',
}, {
  img: myflImg,
  text: '"莓"有烦恼',
}, {
  img: jzjlImg,
  text: '禁止"蕉"绿',
}, {
  img: szjxImg,
  text: '升职加薪',
}, {
  img: jyczImg,
  text: '教育成长',
}, {
  img: hwylImg,
  text: '毫无"鸭梨"',
}, {
  img: jbaxImg,
  text: '"家"倍安心',
}, {
  img: thggImg,
  text: '"桃花"滚滚',
}, {
  img: ylghImg,
  text: '养老规划',
}, {
  img: plrsImg,
  text: '"票"亮人生',
}, {
  img: nnyyImg,
  text: '年年有"鱼"',
}];

const RankingPage = ({ onBack, onNextPage, onGoToFjyj }) => {
  // 弹框显示状态
  const [showPackageModal, setShowPackageModal] = useState(false);
  const [showShareModal, setShowShareModal] = useState(false);

  // 存储用户选择的行李数据
  const [userSelectedItems, setUserSelectedItems] = useState([]);

  // 排行榜数据状态
  const [rankingData, setRankingData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 组件挂载时从localStorage读取用户的行李数据和获取排行榜数据
  useEffect(() => {
    // 读取用户行李数据
    try {
      const savedData = localStorage.getItem('package_data');
      if (savedData) {
        const parsedData = JSON.parse(savedData);
        console.log('RankingPage: 从localStorage读取到打包数据:', parsedData);
        setUserSelectedItems(parsedData.selectedItems || []);
      } else {
        console.log('RankingPage: localStorage中没有打包数据');
        // 如果没有数据，使用默认的前5个项目
        setUserSelectedItems([0, 1, 2, 3, 4]);
      }
    } catch (error) {
      console.error('RankingPage: 读取localStorage中的打包数据失败:', error);
      // 出错时使用默认的前5个项目
      setUserSelectedItems([0, 1, 2, 3, 4]);
    }

    // 获取排行榜数据
    fetchRankingList();
  }, []);

  // 模拟已选择的行李项目（可以从props传入或从状态管理中获取）
  const selectedItems = userSelectedItems; // 使用从localStorage读取的数据

  // 获取排行榜数据的API函数
  const fetchRankingList = async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await ApiService.ranking.getRankingList({
        openId: localStorage.getItem('openId'),
        userId: localStorage.getItem('userId')
    });
    console.log('获取排行榜数据:', response);

      if (response) {
        setRankingData(response);
      } else {
        // 如果API调用失败，使用默认数据
        setRankingData(getDefaultRankingData());
      }
    } catch (error) {
      console.error('获取排行榜数据失败:', error);
      setError('获取排行榜数据失败');
      // 使用默认数据作为备选方案
      setRankingData(getDefaultRankingData());
    } finally {
      setLoading(false);
    }
  };

  // 默认排行榜数据（备选方案）
  const getDefaultRankingData = () => [
  ];

  //回到onGoFjyjPage
  const onGoFjyjPage = () => {
    console.log('RankingPage: 跳转到FjyjPage页面');
    if (onGoToFjyj) {
      onGoToFjyj();
    }
  };

  // 处理点击行李箱
  const handleLuggageClick = () => {
    setShowPackageModal(true);
  };

  // 关闭弹框
  const handleCloseModal = () => {
    setShowPackageModal(false);
  };

  // 关闭分享弹框
  const handleCloseShareModal = () => {
    setShowShareModal(false);
  };

  // 处理分享功能
  const handleShare = (e) => {
    e.stopPropagation(); // 阻止事件冒泡到父元素
    setShowShareModal(true);
  };

  // 刷新排行榜数据
  const refreshRankingData = () => {
    fetchRankingList();
  };

  // 获取排名图标
  const getRankIcon = (rank) => {
    const rankImages = {
      1: dymImg, // 第一名
      2: demImg, // 第二名
      3: dsmImg, // 第三名
    };
    return rankImages[rank] || null;
  };

  // 用户名脱敏处理函数
  const desensitizeName = (userName) => {
    if (!userName || userName.length === 0) {
      return '**';
    }

    // 获取第一个字符
    const firstChar = userName.charAt(0);

    // 如果用户名长度为1，直接返回第一个字符
    if (userName.length === 1) {
      return firstChar;
    }

    // 否则返回第一个字符加**
    return firstChar + '**';
  };

  return (
    <div className="ranking-page">
      <Header />

      <img src={shdyjImg} alt="背景" className='text-bg' />

      {/* 分享区域 */}
      <div className="share-section">
        <div className="share-content">
          <div>来看看<span style={{ color: '#feef04' }}>默契度排名</span>吧</div>
          <div>谁才是最懂TA的</div>
        </div>
      </div>
      <div
        className="ranking-list"
        style={{
          backgroundImage: `url(${mqdphbImg})`,
          backgroundSize: '100% 100%',
          backgroundRepeat: 'no-repeat',
          backgroundPosition: 'center'
        }}
      >
        <div className='rangk-one'></div>
        <div className='ranking-content'>
          {!loading && rankingData.map((player, index) => (
            <div key={index} className="ranking-item" style={{ marginBottom: '5px' }}>
              <div className="ranking-left">
                <div className="rank-badge">
                  <div className="player-info">
                    {getRankIcon(player.rank) ? (
                      <img
                        src={getRankIcon(player.rank)}
                        alt={`第${player.rank}名`}
                        className="rank-image"
                      />
                    ) : (
                      <div className="player-rank">{player.rank}</div>
                    )}
                    <div className="player-name">{desensitizeName(player.userName)}</div>
                  </div>
                </div>
              </div>
              <div className="ranking-center">
                <div className="ranking-center-line"></div>
              </div>
              <div className="ranking-right">
              <div className="player-progress">默契值{player.matchScore} %</div>
                <div className="items-container">
                  {userSelectedItems.map((itemIndex, displayIndex) => (
                    <div key={displayIndex} className="package-item-ranking">
                      <div
                        className="package-item-icon-ranking"
                        style={{
                          backgroundImage: `url(${iconBackImg})`,
                          backgroundSize: '100% 100%',
                          backgroundRepeat: 'no-repeat',
                          backgroundPosition: 'center',
                          position: 'relative'
                        }}
                      >
                        <div
                          className="package-item-img-ranking"
                          style={{
                            backgroundImage: `url(${imagesText[itemIndex]?.img})`,
                            backgroundSize: '100% 100%',
                            backgroundRepeat: 'no-repeat',
                            backgroundPosition: 'center'
                          }}
                        ></div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className='text-btn-rangk-s'>我也要测</div>

      <div className='text-font'>
        <div>*排名规则:按默契度从高到低排序，</div>
        <div>默契度相同时按参与互动时间先后顺序排名(先参与者排名靠前)</div>
      </div>
    </div>
  );
};

export default RankingPage;